package com.example.logindemo.controller;

import com.example.logindemo.entity.User;
import com.example.logindemo.service.UserService;
import com.example.logindemo.utils.CaptchaUtil;
import com.example.logindemo.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Autowired
    private JwtUtil jwtUtil;
    
    @Autowired
    private UserService userService;
    
    @Autowired
    private PasswordEncoder passwordEncoder;

    @GetMapping("/")
    public String index() {
        return "redirect:/login";
    }

    @GetMapping("/login")
    public String loginPage(Model model) {
        // 预先生成验证码
        String captchaCode = CaptchaUtil.generateRandomCode();
        String captchaBase64 = CaptchaUtil.generateCaptchaBase64(captchaCode);
        model.addAttribute("captchaBase64", captchaBase64);
        model.addAttribute("captchaCode", captchaCode);
        return "login";}

    // 注册页面
    @GetMapping("/register")
    public String registerPage() {
        return "register";}

    // 处理注册请求
    @PostMapping("/register")
    public String register(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("confirmPassword") String confirmPassword,
                          @RequestParam(required = false, name = "email") String email,
                          @RequestParam(required = false, name = "phoneNumber") String phoneNumber,
                          Model model) {
        // 验证密码是否一致
        if (!password.equals(confirmPassword)) {
            model.addAttribute("error", "两次输入的密码不一致");
            return "register";}

        // 验证用户名长度
        if (username.length() < 3 || username.length() > 20) {
            model.addAttribute("error", "用户名长度必须在3-20个字符之间");
            return "register";}

        // 验证密码长度
        if (password.length() < 6) {
            model.addAttribute("error", "密码长度不能少于6个字符");
            return "register";}

        try {
            // 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            // 使用密码编码器加密密码
            newUser.setPassword(passwordEncoder.encode(password));
            newUser.setEmail(email);
            newUser.setPhoneNumber(phoneNumber);

            // 保存用户到数据库
            userService.createUser(newUser);

            // 注册成功，提示用户并跳转到登录页面
            model.addAttribute("success", "注册成功！请使用新账号登录");
            // 预先生成验证码
            String captchaCode = CaptchaUtil.generateRandomCode();
            String captchaBase64 = CaptchaUtil.generateCaptchaBase64(captchaCode);
            model.addAttribute("captchaBase64", captchaBase64);
            model.addAttribute("captchaCode", captchaCode);
            return "login";} catch (RuntimeException e) {
            // 处理用户已存在等异常
            model.addAttribute("error", e.getMessage());
            return "register";}
    }

    @PostMapping("/login")
    public String login(@RequestParam("username") String username,
                       @RequestParam("password") String password,
                       @RequestParam("captcha") String captcha,
                       @RequestParam("captchaCode") String captchaCode,
                       Model model, HttpServletResponse response) {
        // 验证验证码
        if (!captcha.equalsIgnoreCase(captchaCode)) {
            model.addAttribute("error", "验证码错误");
            // 重新生成验证码
            String newCaptchaCode = CaptchaUtil.generateRandomCode();
            String captchaBase64 = CaptchaUtil.generateCaptchaBase64(newCaptchaCode);
            model.addAttribute("captchaBase64", captchaBase64);
            model.addAttribute("captchaCode", newCaptchaCode);
            return "login";
        }

        // 使用UserService进行用户验证
        User user = userService.getUserByUsername(username);
        
        if (user != null && passwordEncoder.matches(password, user.getPassword())) {
            // 登录成功，生成JWT token
            String token = jwtUtil.generateToken(username);
            
            // 将token存储到cookie中，以便前端可以在请求头中使用
            Cookie cookie = new Cookie("jwtToken", token);
            cookie.setPath("/");
            cookie.setHttpOnly(true); // 防止XSS攻击
            cookie.setMaxAge(24 * 60 * 60); // 24小时
            response.addCookie(cookie);
            
            // 添加用户信息到模型，方便前端访问
            model.addAttribute("user", user);
            // 登录成功后跳转到评价列表页面
            return "redirect:/reviews";
        } else {
            model.addAttribute("error", "用户名或密码错误");
            // 重新生成验证码
            String newCaptchaCode = CaptchaUtil.generateRandomCode();
            String captchaBase64 = CaptchaUtil.generateCaptchaBase64(newCaptchaCode);
            model.addAttribute("captchaBase64", captchaBase64);
            model.addAttribute("captchaCode", newCaptchaCode);
            return "login";
        }
    }

    // 评价列表页面
    @GetMapping("/reviews")
    public String reviews() {
        return "reviews";
    }

    // 评价详情页面
    @GetMapping("/dashboard")
    public String dashboard(@RequestParam(required = false) String runOrderId, Model model) {
        // 如果有runOrderId参数，可以将其传递给页面用于展示特定跑单的评价
        if (runOrderId != null) {
            model.addAttribute("runOrderId", runOrderId);
        }
        return "dashboard";
    }
    
    @GetMapping("/profile")
    public String profile() {
        // 个人信息页面
        return "profile";
    }

    @GetMapping("/captcha")
    @ResponseBody
    public String refreshCaptcha(HttpSession session) {
        String captchaCode = CaptchaUtil.generateRandomCode();
        String captchaBase64 = CaptchaUtil.generateCaptchaBase64(captchaCode);
        return captchaBase64;
    }

    @GetMapping("/logout")
    public String logout(HttpServletResponse response) {
        // 清除JWT cookie
        Cookie cookie = new Cookie("jwtToken", null);
        cookie.setPath("/");
        cookie.setHttpOnly(true);
        cookie.setMaxAge(0); // 立即过期
        response.addCookie(cookie);
        return "redirect:/login";
    }
}